$(function () {
    function getSearchString(key) {
        var str = window.location.search;
        str = str.substring(1, str.length); // 获取URL中?之后的字符（去掉第一位的问号）
        // 以&分隔字符串，获得类似name=xiaoli这样的元素数组
        var arr = str.split("&");
        var obj = new Object();
        // 将每一个数组元素以=分隔并赋给obj对象
        for (var i = 0; i < arr.length; i++) {
            var tmp_arr = arr[i].split("=");
            obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
        }
        return obj[key];
    }
    id = getSearchString('gid');
    // console.log(id);


    loadGoods();
    async function loadGoods() {
        var tips = document.getElementsByClassName("tips")[0];
        var search_bar = document.querySelector(".search_bar");
        var orderColBox = document.querySelector(".orderColBox");
        var select = document.querySelector(".select");
        var prev = document.querySelector(".prev");
        var next = document.querySelector(".next");
        var pageTips = document.querySelector(".pageTips");
        // var key = "";   // 默认查询所有
        // var orderCol = "id";  // 默认按id排序
        // var pageNum = 20;
        // var pageIndex = 1;
        searchGoodsById({ id }).then(function (result) {
            var { status, detail, list, maxPage } = result;
            // console.log(result);
            var html = "";
            var html1 = "";
            list.forEach(({ id, goodsId, goodsName, goodsImg, goodsPrice }) => {
                html += ` <h2>${goodsName}</h2>
        <div>
            京 东 价:￥ <span class="price">${goodsPrice}</span> 降价通知
        </div>
        <div class="buyNum">
            <span class="reduce">-</span>
            <input type="number" value="1" class="number">
            <span class="add">+</span>
        </div>
        <div class="provinces">
            <span>配送至：</span>
            <select class="province">
                <option value="">请选择省份</option>
            </select>
            <select class="city">
                <option value="">请选择市区</option>
            </select>
            <select class="town">
                <option value="">请选择县区</option>
            </select>
        </div>
        <button class="addToCar">
            加入购物车
        </button> `
                html1 += `<div class="bigImg">
            <div class="shadow"></div>
            <img src="${goodsImg}" alt="" class="shadowImg">
        </div>
        <div class="bigImgShow">
            <img src="${goodsImg}" alt="" class="ImgShow">
        </div>`
            })
            $(".left").html(html1);
            $(".right").html(html);


            //商品增加/减少
            var p = $(".price").text();
            $(document).on("click", ".add", function () {
                // this -> 执行委托事件的元素(事件源)
                var val = $(this).prev().val();
                // console.log($(this).prev().val());
                val++;
                $(this).prev().val(val);

                // console.log($(".price").text());
                $(".price").text((val * p * 1).toFixed(2));
            })

            $(document).on("click", ".reduce", function () {
                var val = $(this).next().val();
                $(".price").text((val * p * 1).toFixed(2));
                if (val <= 1) {
                    $(this).off("click");
                } else {
                    val--;
                    $(this).next().val(val);
                    $(".price").text((val * p * 1).toFixed(2));
                }
            })

            $(document).on("blur", ".number", function () {
                var val = $(".number").val();
                console.log($(".number").val());
                $(".price").text((val * p * 1).toFixed(2));
            })

            //省市区三级联动
            var province = document.getElementsByClassName("province")[0];
            var city = document.getElementsByClassName("city")[0];
            var town = document.getElementsByClassName("town")[0];
            var xhr = new XMLHttpRequest();

            xhr.open("get", "../data/proData.json", true);

            xhr.send();

            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var result = JSON.parse(xhr.responseText);
                    // console.log(result);
                    var { list: proList } = result;
                    var html = `<option value="">请选择省份</option>`;
                    proList.forEach(function (item) {
                        var { city_id, name } = item;
                        // <option value="">请选择省份</option>
                        html += `<option value="${city_id}">${name}</option>`;
                    })
                    province.innerHTML = html;
                    province.onchange = function () {
                        var cityId = this.value;
                        if (cityId) {
                            // console.log(cityId, proList);
                            var arr = proList.filter(function (item) {
                                return cityId == item.city_id;
                            });
                            var thisPro = arr[0];
                            // console.log(thisPro);
                            var { list: cityList } = thisPro;
                            var html = '<option value="">请选择市区</option>';
                            cityList.forEach(function (item) {
                                var { city_id, name } = item;
                                html += `<option value="${city_id}">${name}</option>`;
                            })
                            city.innerHTML = html;
                            town.innerHTML = `<option value="">请选择县区</option>`;
                            // town.style.display = "none";


                            city.onchange = function () {
                                var cityId = this.value;
                                if (cityId) {
                                    // console.log(cityId, proList);
                                    var arr = cityList.filter(function (item) {
                                        return cityId == item.city_id;
                                    });
                                    var thisCity = arr[0];
                                    // console.log(thisCity);
                                    var { list: townList } = thisCity;
                                    if (townList) {
                                        town.style.display = "inline-block";
                                        console.log(townList);
                                        var html = '<option value="">请选择县区</option>';
                                        townList.forEach(function (item) {
                                            var { city_id, name } = item;
                                            html += `<option value="${city_id}">${name}</option>`;
                                        })
                                        town.innerHTML = html;
                                    } else {
                                        town.style.display = "none";
                                    }
                                } else {
                                    town.innerHTML = '<option value="">请选择县区</option>';
                                }
                            }
                        } else {
                            city.innerHTML = '<option value="">请选择市区</option>';
                            town.innerHTML = '<option value="">请选择县区</option>';
                        }
                    }
                }
            }

            //轮播图
            var left = document.querySelector(".left");
            var bigImg = document.querySelector(".bigImg");
            var shadow = document.querySelector(".shadow");
            var ImgShow = document.querySelector(".ImgShow");
            var bigImgShow = document.querySelector(".bigImgShow");
            var shadowImg = document.querySelector(".shadowImg");

            bigImg.onmouseenter = function (e) {
                bigImgShow.style.display = "block";
                shadow.style.display = "block";
            }

            bigImg.onmouseleave = function (e) {
                bigImgShow.style.display = "none";
                shadow.style.display = "none";
            }

            bigImg.onmousemove = function (e) {
                var e = e || window.event;
                var scale = ImgShow.clientHeight / shadowImg.clientHeight;
                var maxLeft = bigImg.clientWidth - shadow.clientWidth + 30;
                var maxTop = bigImg.clientHeight - shadow.clientHeight + 30;

                var x = e.pageX - bigImg.offsetLeft - shadow.clientWidth / 2;
                var y = e.pageY - bigImg.offsetTop - shadow.clientHeight / 2;

                if (x < 30) x = 30;
                if (x >= maxLeft) x = maxLeft;
                if (y < 30) y = 30;
                if (y >= maxTop) y = maxTop;

                shadow.style.left = x + "px";
                shadow.style.top = y + "px";

                ImgShow.style.left = -scale * x + "px";
                ImgShow.style.top = -scale * y + "px";
            }
        }).catch(err => {
            // tbody.innerHTML = `<tr><td colspan="9">暂无数据</td></tr>`;
            throw err;
        });
    }

})